﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FormQQOnLineCheck.cs" company="">
//   
// </copyright>
// <summary>
//   The form qq on line check.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace NetworkSupervisor
{
    using System;
    using System.Windows.Forms;

    using DevExpress.XtraEditors;
    using DevExpress.XtraGrid;
    using DevExpress.XtraGrid.Views.Grid;

    using NetworkSupervisor.Helper;
    using NetworkSupervisor.Model.NetworkSupervisor;

    /// <summary>The form qq on line check.</summary>
    public partial class FormQQOnLineCheck : DevExpress.XtraEditors.XtraForm
    {
        #region Fields

        /// <summary>The loading.</summary>
        private FormLoadProgress loading = null;

        /// <summary>The stop it.</summary>
        private bool stopIt;

        /// <summary>
        /// 时间间隔，以分钟为单位
        /// </summary>
        private int timeSpan;

        #endregion

        #region Constructors and Destructors

        /// <summary>Initializes a new instance of the <see cref="FormQQOnLineCheck"/> class.</summary>
        public FormQQOnLineCheck()
        {
            this.InitializeComponent();
        }

        #endregion

        #region Methods

        /// <summary>The form qq on line check_ form closing.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void FormQQOnLineCheck_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.btnStart.Enabled == false)
            {
                XtraMessageBox.Show("正在监测，请先停止监测后再退出");
                e.Cancel = true;
            }
            else
            {
                this.stopIt = true;
            }
        }

        /// <summary>The form qq on line check_ load.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void FormQQOnLineCheck_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;

            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
            this.stopIt = false;
        }

        /// <summary>The form qq on line check_ resize.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void FormQQOnLineCheck_Resize(object sender, EventArgs e)
        {
            this.groupControl2.Width = this.Width / 2 + 100;
        }

        /// <summary>The form qq on line check_ shown.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void FormQQOnLineCheck_Shown(object sender, EventArgs e)
        {
            this.btnStart.Enabled = false;
            this.loading = new FormLoadProgress("正在加载数据，请等候...", this.XPCQQ列表.Count);
            this.BeginInvoke(new MethodInvoker(() => this.loading.ShowDialog()));

            System.Threading.ThreadPool.QueueUserWorkItem(this.initOnlineCountAndLastOnLineTime);
        }

        /// <summary>The btn export_ click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            GridControl gridControl = this.gridControl1;
            string fileName = "在线情况统计列表";

            GridExportHelper.ExportGridToExcel(gridControl, fileName);
        }

        /// <summary>The btn start_ click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            string text = this.txtSpan.Text;
            if (text == string.Empty)
            {
                XtraMessageBox.Show("请输入时间间隔");
                return;
            }

            this.timeSpan = Convert.ToInt32(text);
            if (this.timeSpan < 30)
            {
                if (XtraMessageBox.Show("建议时间间隔不要少于30分钟", string.Empty, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                {
                    return;
                }
            }

            this.btnStart.Enabled = false;
            this.btnStop.Enabled = true;
            this.txtSpan.Enabled = false;
            this.timeStart.Enabled = this.timeEnd.Enabled = false;
            this.stopIt = false;
            this.dataGridView1.Rows.Clear();
            this.timer1.Interval = this.timeSpan * 60 * 1000;
            this.timer1.Start();
            System.Threading.ThreadPool.QueueUserWorkItem(this.callBack);
        }

        /// <summary>The btn stop_ click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("正在监控QQ，是否确认退出监控？", string.Empty, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }

            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
            this.txtSpan.Enabled = true;
            this.timeStart.Enabled = this.timeEnd.Enabled = true;
            this.gridControl1.Enabled = true;

            this.stopIt = true;
            this.progressBarControl1.Position = this.progressBarControl1.Properties.Maximum;
            this.timer1.Stop();
        }

        /// <summary>The call back.</summary>
        /// <param name="state">The state.</param>
        private void callBack(object state)
        {
            this.gridControl1.Enabled = false;

            try
            {
                TimeSpan now = DateTime.Now.TimeOfDay;
                TimeSpan tStart = this.timeStart.Time.TimeOfDay;
                TimeSpan tEnd = this.timeEnd.Time.TimeOfDay;
                if (tEnd > tStart)
                {
                    if (now < tStart || now > tEnd)
                    {
                        return;
                    }
                }
                else
                {
                    if (now < tStart && now > tEnd)
                    {
                        return;
                    }
                }

                int onLineCount = 0;
                this.UIThread(() => this.dataGridView1.Rows.Clear());
                int rowCount = this.gridView1.RowCount;
                for (int i = 0; i < rowCount; i++)
                {
                    taQQ列表 item = this.gridView1.GetRow(i) as taQQ列表;
                    bool onLine = false;
                    try
                    {
                        onLine = QQHelper.CheckQQOnLine(item.QQ);
                    }
                    catch
                    {
                    }

                    this.UIThread(
                        () =>
                            {
                                item.是否在线 = onLine;
                                item.Save();
                            });
                    this.UIThread(() => this.gridView1.FocusedRowHandle = i);
                    this.UIThread(() => this.progressBarControl1.Position = (int)((double)(i + 1) * 1000 / (double)rowCount));

                    DateTime dateTime = DateTime.Now;
                    this.UIThread(
                        () =>
                            {
                                taQQ在线纪录 item2 = new taQQ在线纪录(this.session1);
                                item2.QQ = item.QQ;
                                item2.在线时间 = dateTime;
                                item2.在线状态 = onLine ? 1 : 0;
                                item2.Save();
                            });

                    if (onLine)
                    {
                        onLineCount++;
                        this.UIThread(() => this.dataGridView1.Rows.Add(new[] { onLineCount.ToString(), item.单位, item.姓名, item.QQ }));
                        this.UIThread(() => item.Set上次在线时间());
                        this.UIThread(() => item.Set在线次数());
                    }

                    if (this.stopIt)
                    {
                        return;
                    }
                }
            }
            catch
            {
            }

            this.gridControl1.Enabled = true;
        }

        /// <summary>The data grid view 1_ double click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            if (this.dataGridView1.RowCount < 1)
            {
                return;
            }

            string qqCode = this.dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
            string url = QQHelper.GetQQOnlineChatUrl(qqCode);
            System.Diagnostics.Process.Start(url);
        }

        /// <summary>The grid view 1_ custom draw row indicator.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        /// <summary>The grid view 1_ double click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            if (this.gridView1.RowCount < 1)
            {
                return;
            }

            string qq = this.gridView1.GetFocusedRowCellDisplayText("QQ");
            string url = QQHelper.GetQQOnlineChatUrl(qq);
            System.Diagnostics.Process.Start(url);
        }

        /// <summary>The init online count and last on line time.</summary>
        /// <param name="state">The state.</param>
        private void initOnlineCountAndLastOnLineTime(object state)
        {
            try
            {
                int count = this.XPCQQ列表.Count;
                int onLineCount = 0;
                for (int i = 0; i < count; i++)
                {
                    taQQ列表 item = this.XPCQQ列表[i] as taQQ列表;
                    this.UIThread(() => item.Set在线次数());
                    if (item.在线次数 > 0)
                    {
                        this.UIThread(() => item.Set上次在线时间());
                    }

                    this.UIThread(() => this.loading.mySetProgressPosition(i + 1));
                    if (item.是否在线)
                    {
                        onLineCount++;
                        int lineCount = onLineCount;
                        this.UIThread(() => this.dataGridView1.Rows.Add(new object[] { lineCount, item.单位, item.姓名, item.QQ, item.标识号 }));
                    }
                }

                this.UIThread(() => this.btnStart.Enabled = true);
                this.UIThread(() => this.loading.Close());
            }
            catch
            {
            }
        }

        /// <summary>The text edit 1_ key press.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void textEdit1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        /// <summary>The timer 1_ tick.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(this.callBack);
        }

        #endregion
    }
}